#include "film.h"
#include "utils.h"

using namespace tls;

void film::process(){
  image=(png_bytep*)malloc(height * sizeof(png_bytep));
  for(int i=0;i<height;++i){
    image[i]=(png_bytep)std::malloc(3 * width * sizeof(png_byte));
  }

  for(int y=0;y<height;++y){
    for(int x=0;x<width;++x){
      png_bytep ptr=image[y]+3*x;

      vec3 color=f[y*width + x];
      for(int e=0;e<3;++e){
	real v=clamp(color[e]);
	ptr[e]=v * 255;
      }
    }
  }
}

void film::write(const char* filename)const{
  std::FILE* fp;
  png_structp png_ptr;
  png_infop info_ptr;

  fp=std::fopen(filename,"w");

  png_ptr=png_create_write_struct(PNG_LIBPNG_VER_STRING,0,0,0);

  info_ptr=png_create_info_struct(png_ptr);

  png_init_io(png_ptr,fp);
  png_set_IHDR(png_ptr,info_ptr,width,height,
	       8,PNG_COLOR_TYPE_RGB,PNG_INTERLACE_NONE,
	       PNG_COMPRESSION_TYPE_BASE,PNG_FILTER_TYPE_BASE);
  png_write_info(png_ptr,info_ptr);

  //png_write_image(png_ptr,buffer);
  for(int i=height-1;i>=0;--i){
    png_write_row(png_ptr,image[i]);
  }

  png_write_end(png_ptr,0);

  //finalise:
  fclose(fp);
  png_free_data(png_ptr,info_ptr,PNG_FREE_ALL,-1);
  png_destroy_write_struct(&png_ptr,(png_infopp)0);

}
